package com.zhlab.mybatisdemo.chapter1;

import com.zhlab.mybatisdemo.web.entity.SysAdminUser;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName Chapter1DemoApplication
 * @Description //Chapter1DemoApplication
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/12/29 0029 上午 10:15
 **/
@SpringBootApplication
public class Chapter1DemoApplication {
    public static void main(String[] args) throws Exception {
        /*
        * 存储持久化数据常常会用到数据库
        * 传统数据库操作:
        * 加载驱动程序包
        * 与数据库建立连接
        * 拼装和执行 SQL语句
        * 获取数据库结果，数据转化操作
        * 关闭连接
        * */
        String url = "jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=UTC";
        String userName = "root";
        String password = "root";

        SysAdminUser userParam = new SysAdminUser();
        userParam.setDeptId(5);

        // 第一步：加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 第二步：获得数据库的连接
        Connection conn = DriverManager.getConnection(url, userName, password);

        // 第三步：创建语句并执行
        Statement stmt = conn.createStatement();
        ResultSet resultSet = stmt.executeQuery("SELECT * FROM `sys_admin_user` WHERE dept_id = " + userParam.getDeptId() + ";");

        // 第四步：处理数据库操作结果
        List<SysAdminUser> userList = new ArrayList<>();
        while(resultSet.next()){
            SysAdminUser user = new SysAdminUser();
            user.setAdminUserId(resultSet.getInt("admin_user_id"));
            user.setUserName(resultSet.getString("user_name"));
            user.setEmail(resultSet.getString("email"));
            user.setNickName(resultSet.getString("nick_name"));
            user.setDeptId(resultSet.getInt("dept_id"));
            userList.add(user);
        }

        // 第五步：关闭连接
        stmt.close();

        for (SysAdminUser user : userList) {
            System.out.println("userName : " + user.getUserName() + " ;  email : " + user.getEmail());
        }
    }
}
